package com.hz.cheetah.common.net;

/**
 * Created by yangchuan on 16/6/28.
 */
import com.hz.cheetah.common.util.StringUtil;

import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;


/**
 *
 */
public class NetUtil {

    public static String getLocalIP4Addr() throws SocketException {
        Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements())
        {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            //System.out.println(netInterface.getName());
            Enumeration addresses = netInterface.getInetAddresses();
            while (addresses.hasMoreElements())
            {
                ip = (InetAddress) addresses.nextElement();
                if (ip != null && ip instanceof Inet4Address)
                {
                   return ip.getHostAddress();
                }
            }
        }

       return null;
    }

    /**
     * 将ip和端口保存为字符串
     * @param serviceAddress
     * @return
     * @throws Exception
     */
    public static long stringIpPort2ServerUID(String serviceAddress)  {
        String[] array = StringUtil.split(serviceAddress, ":");
        return stringIpPort2ServerUID(array);

    }

    public static long stringIpPort2ServerUID(String[] array)  {
        final String[] ipNums = array[0].split("\\.");
        return Long.parseLong(array[1]) << 32 | (Long.parseLong(ipNums[0]) << 24)
                | (Long.parseLong(ipNums[1]) << 16)
                | (Long.parseLong(ipNums[2]) << 8)
                | (Long.parseLong(ipNums[3]));
    }

    /**
     * 将字符串转化为ip和端口
     * @param sid
     * @return
     */
    public static String serverUID2StringIpPort(long sid) {
        StringBuilder bu = new StringBuilder();
        bu.append(((int) sid >> 24) & 0xff).append('.')
                .append(((int) sid >> 16) & 0xff).append('.')
                .append(((int) sid >> 8) & 0xff).append('.')
                .append((int) sid & 0xff).append(':')
                .append((int)(( sid >> 32) & -1L));
        return bu.toString();
    }
}

